from django.db import models
from api.models.wechat_user import WechatUser
import json

class Feedback(models.Model):
    """反馈意见模型"""
    FEEDBACK_TYPE_CHOICES = [
        ('bug', '问题反馈'),
        ('suggestion', '功能建议'),
        ('complaint', '投诉'),
        ('other', '其他')
    ]
    
    STATUS_CHOICES = [
        ('pending', '待处理'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('rejected', '已拒绝')
    ]
    
    user = models.ForeignKey(WechatUser, on_delete=models.CASCADE, verbose_name='用户')
    feedback_type = models.CharField(max_length=20, choices=FEEDBACK_TYPE_CHOICES, verbose_name='反馈类型')
    content = models.TextField(verbose_name='反馈内容')
    contact = models.CharField(max_length=50, blank=True, null=True, verbose_name='联系方式')
    images = models.TextField(default='[]', blank=True, verbose_name='图片列表')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    reply = models.TextField(blank=True, null=True, verbose_name='回复内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '反馈意见'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.user.nickname} - {self.get_feedback_type_display()}"
    
    def get_images(self):
        """获取图片列表"""
        try:
            return json.loads(self.images)
        except json.JSONDecodeError:
            return []
    
    def set_images(self, images):
        """设置图片列表"""
        if isinstance(images, list):
            self.images = json.dumps(images)
        else:
            self.images = '[]'
    
    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'user': {
                'id': self.user.id,
                'nickname': self.user.nickname,
                'avatar': self.user.avatar
            },
            'feedback_type': self.feedback_type,
            'feedback_type_display': self.get_feedback_type_display(),
            'content': self.content,
            'contact': self.contact,
            'images': self.get_images(),
            'status': self.status,
            'status_display': self.get_status_display(),
            'reply': self.reply,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        } 